<!-- 
 @Author: Havery   
 @Date: 2021-01-13 09:09:15   
 @function:接口安全
----------------------------------------------------------  
 @Last Modified by:  LW
 @Modified function:修改无法加入黑名单和删除黑名单BUG
 -->
<template>
  <div style="height: 100%">
    <el-row :gutter="12">
      <el-col :span="12">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span class="tit">
              <i class="iconfont iconjibenxinxi"></i>接口请求走势图
            </span>
          </div>
          <div class="optbtns message" ref="messageRef">
             <div id="lineChart" style="width:100%;height:100%;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span class="tit">
              <i class="iconfont iconjiekou"></i>高频请求接口信息
            </span>
          </div>
          <div class="optbtns" ref="apiRef">
            <div id="main_columnar" style="width:100%;height:100%;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="12" style="margin-top: 10px">
       <el-col :span="12">
        <el-card shadow="always">
          <div slot="header" class="clearfix">
            <span class="tit">
              <i class="iconfont iconjibenxinxi"></i>警告信息
            </span>
          </div>
          <div class="optbtns message" ref="warningRef">
              <el-card class="box-card card1" shadow="hover">
                  <div class="searchBox">
                    <!-- 搜索筛选 -->
                    <el-form :inline="true" :model="formSearch" class="user-search">
                      <el-form-item label="搜索：">
                        <el-input size="mini" v-model="formSearch.parameters" placeholder="请输入关键字"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleSearch()">搜索</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </el-card>
              <el-card class="box-card" shadow="hover">
                <!--列表  @selection-change="selectChange" 复选-->
                <el-table
                  class="ptab"
                  border
                  stripe
                  size="small" 
                  ref="multipleTable"
                  :data="listData"
                  highlight-current-row
                  v-loading="loading"
                  element-loading-text="拼命加载中"
                  style="width: 99%"
                  :height="tableHeight"
                >
                  <el-table-column label="序号" width="70px">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                  </el-table-column>
                  <el-table-column align="center"  prop="request_path" label="请求地址" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column align="center"  prop="request_ip" label="客户端ip" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column align="center"  prop="frequency" label="请求频率" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column align="center"  prop="statistics_time" label="统计时间" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-umbrella"
                        class="btnRed"
                        @click="handleBlacklist(scope.$index, scope.row)"
                      >加入黑名单</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页组件 pageparm返回的分页参数信息 pageListInfo为分页组件回掉方法-->
                <Pagination v-bind:child-msg="pageparm" @callFather="pageListInfo"></Pagination>
              </el-card>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span class="tit">
              <i class="iconfont iconjiekou"></i>黑名单
            </span>
          </div>
          <div class="optbtns" ref="blacklistRef">
           <el-card class="box-card card1" shadow="hover">
                <div class="searchBox">
                  <!-- 搜索筛选 -->
                  <el-form :inline="true" :model="formSearch1" class="user-search">
                    <el-form-item label="搜索：">
                      <el-input size="mini" v-model="formSearch1.parameters" placeholder="请输入关键字"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-search"
                        @click="handleSearch1()"
                      >搜索</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-card>
              <el-card class="box-card" shadow="hover">
                <!--列表  @selection-change="selectChange" 复选-->
                <el-table
                  size="small" 
                  ref="multipleTable1"
                  :data="listData1"
                  highlight-current-row
                  v-loading="loading1"
                  border
                  element-loading-text="拼命加载中"
                  style="width: 99%"
                  :height="tableHeight"
                >
                  <el-table-column label="序号" width="70px">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                  </el-table-column>
                  <el-table-column align="center"  prop="request_ip" label="客户端ip" :show-overflow-tooltip="true"></el-table-column>
                  <el-table-column align="center"  prop="name_type" label="类型" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                      <div>{{ scope.row.name_type == 100 ? "预警" : "黑名单" }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-remove"
                        class="btnRed"
                        @click="handleRemove(scope.$index, scope.row)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页组件 pageparm返回的分页参数信息 pageListInfo为分页组件回掉方法-->
                <Pagination v-bind:child-msg="pageparm1" @callFather="pageListInfo1"></Pagination>
              </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
//引用对象【不同业务，需要各玩各的。别一个界面就完成所有。业务复杂以后，搞死一堆人】
import Pagination from "@/components/common/pagination"; //分页组建
import InterfacesecurityHttp from "@/api/safe/interfacesecurity"; //http
import Echarts from "echarts";
//定义变量
const {
  loadInterfaceWarning, //获取分页消息信息
  loadBlacklist, //第二个列表
  addBalckList,//加入黑名单
  removeBalckList,//删除接口黑名单
} = InterfacesecurityHttp;
export default {
  //注册组件
  components: {
    Echarts, //
    Pagination //分页visitsnumber
  },
  data() {
    return {
      myChart: null,
      //列表相关
      loading: false, //是显示加载
      tableHeight: window.innerHeight * 0.28, //表格高度
      pageparm: { currentPage: 1, pageSize: 16, total: 0 }, //分页参数
      listData: [], //表格返回信息
      formSearch: {
        //请求数据参数
        page: 1,
        limit: 16,
        field: "",
        order: "",
        parameters: "" //关键字
      },
      ///第二个列表
      loading1: false, //是显示加载
      pageparm1: { currentPage: 1, pageSize: 16, total: 0 }, //分页参数
      listData1: [], //表格返回信息
      formSearch1: {
        //请求数据参数
        page: 1,
        limit: 16,
        field: "",
        order: "",
        parameters: "" //关键字
      }
    };
  },
  /**html加载完成之前，执行。执行顺序：父组件-子组件 */
  created() {
  },
  /**[页面初始化方法]html加载完成后执行。执行顺序：子组件-父组件*/
  mounted() {
    //第一个表格
    this.loadInterfaceWarning();
    //第二个表格
    this.loadBlacklist();
    //获取实时信息
    this.loadInterfaceRequest();
    //调整高度
    this.adjustHeight();
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
     //调整高度
    adjustHeight() {
      var h = document.documentElement.clientHeight || document.body.clientHeight;
      this.$refs.messageRef.style.height = h * 0.3 + "px";
      this.$refs.apiRef.style.height = h * 0.3 + "px";
      this.$refs.warningRef.style.height = h * 0.41 + "px";
      this.$refs.blacklistRef.style.height = h * 0.41 + "px";
    },
    ///////////////////////////////////////////////////////////////////////////////////////
    //获取实时信息
    loadInterfaceRequest() {
      let self = this;
      let signalRUrl = this.$store.state.config.devopsURI + "/apiMonitorLog";
      this.$signalR.startCon(signalRUrl, function(connection) {

        let beginTime = self.$moment(new Date().setSeconds(-60)).format("YYYY-MM-DD HH:mm:ss");
        let endTime = self.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        ///折线图
        connection.on("InterfaceRequestMsg", function(result) {
          if (result.code == 1000) {
            self.loadLineEchart(result);
          }
        });
        connection
          .invoke("InterfaceRequestInfo", beginTime, endTime)
          .catch(function(err) {
            return console.error(err.toString());
          });
        let timer = setInterval(function() {
          if (document.getElementById("lineChart")) {
            beginTime = self
              .$moment(new Date().setSeconds(-60))
              .format("YYYY-MM-DD HH:mm:ss");
            endTime = self.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
            connection
              .invoke("InterfaceRequestInfo", beginTime, endTime)
              .catch(function(err) {
                return console.error(err.toString());
              });
          } else {
            clearInterval(this.timer);
          }
        }, 10000);

        //柱状图
        connection.on("HighFrequencyInterfaceMsg", function(result) {
          if (result.code == 1000) {
            self.loadHighFrequencyInterface(result);
          }
        });
        connection
          .invoke("HighFrequencyInterfaceInfo", beginTime, endTime)
          .catch(function(err) {
            return console.error(err.toString());
          });

        let timer1 = setInterval(function() {
          if (document.getElementById("main_columnar")) {
            beginTime = self
              .$moment(new Date().setSeconds(-60))
              .format("YYYY-MM-DD HH:mm:ss");
            endTime = self.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
            connection
              .invoke("HighFrequencyInterfaceInfo", beginTime, endTime)
              .catch(function(err) {
                return console.error(err.toString());
              });
          } else {
            clearInterval(this.timer1);
          }
        }, 10000);
      });
    },
    //加载折线图
    loadLineEchart(result) {
      this.myChart = Echarts.init(document.getElementById("lineChart"));
      var option = {
        tooltip: {
          trigger: "axis"
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: result.data != null ? result.data.xAxis : []
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            type: "line",
            label: {
              show: true
            },
            data: result.data != null ? result.data.yAxis : [],
            lineStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "red" // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "blue" // 100% 处的颜色
                  }
                ],
                global: false // 缺省为 false
              }
            }
          }
        ],
        grid: {
          show: false,
          x: 50,
          x2: 40,
          y: 32
        }
      };
      this.myChart.setOption(option, true);
      this.myChart.resize();
    },
    //获取高频接口
    loadHighFrequencyInterface(result) {
      try {
        this.myChart = Echarts.init(document.getElementById("main_columnar"));
        var interfaceOption = {
          tooltip: {
            //鼠标悬浮弹窗提示
            trigger: "item",
            formatter: function(params, ticket, callback) {
              var res =
                params.data.name +
                "<br/>" +
                "请求次数" +
                ":" +
                params.data.value +
                "次";
              return res;
            }
          },
          xAxis: [
            {
              show: true,
              type: "value"
            }
          ],
          yAxis: [
            {
              type: "category",
              data: result.data != null ? result.data.yAxis : []
            }
          ],
          series: [
            {
              name: "请求次数",
              type: "bar",
              barMaxWidth: 30, // 最大宽度
              data: result.data != null ? result.data.xAxis : [],
              itemStyle: {
                normal: {
                  label: {
                    show: true,
                    position: "right",
                    formatter: function(params, ticket, callback) {
                      var res = params.data.value + "次";
                      return res;
                    }
                  }
                }
              }
            }
          ],
          grid: {
            show: false,
            x: 50,
            x2: 40,
            y: 32
          }
        };
        this.myChart.setOption(interfaceOption, true);
        this.myChart.resize();
      } catch (error) {
        let a = error;
      }
    },
    ////////////////////////////////////////////////////////////////////////////////////
    //第一个表格
    loadInterfaceWarning() {
      this.loading = true;
      loadInterfaceWarning(this.formSearch).then(response => {
        let data = response.data;
        if (data.Code === 1000) {
          this.listData = data.Data;
          //分页赋值
          this.pageparm.currentPage = this.formSearch.page;
          this.pageparm.pageSize = this.formSearch.limit;
          this.pageparm.total = data.Count;
        } else {
          this.listData = [];
          this.pageparm.currentPage = this.formSearch.page;
          this.pageparm.pageSize = this.formSearch.limit;
          this.pageparm.total = data.Count;
        }
        this.loading = false;
      });
    },
    //第二个表格
    loadBlacklist() {
      this.loading1 = true;
      loadBlacklist(this.formSearch1).then(response => {
        let data = response.data;
        if (data.Code === 1000) {
          this.listData1 = data.Data;
          //分页赋值
          this.pageparm1.currentPage = this.formSearch1.page;
          this.pageparm1.pageSize = this.formSearch1.limit;
          this.pageparm1.total = data.Count;
        } else {
          this.listData1 = [];
          this.pageparm1.currentPage = this.formSearch1.page;
          this.pageparm1.pageSize = this.formSearch1.limit;
          this.pageparm1.total = data.Count;
        }
        this.loading1 = false;
      });
    },
    //删除
    handleRemove(index, row) {
      let self=this;
      this.$messageTip.boxWarning("确定要删除吗?")
        .then(() => {
          let par = {
            ip: row.request_ip
          };
          removeBalckList(par).then(response => {
            let data = response.data;
            if (data.Code === 1000) {
              self.$messageTip.success(data.Msg);
              self.loadBlacklist();
            } else {
              self.$messageTip.warning(data.Msg); 
            }
          });
        })
        .catch(() => {
          this.$messageTip.info("已取消删除！"); 
        });
    },
    //加入黑名单
    handleBlacklist(index, row) {
      let self=this;
      this.$messageTip.boxWarning("确定要删除吗?")
        .then(() => {
          let par = {
            ip:row.request_ip
          };
          addBalckList(par).then(response => {
            let data = response.data;
            if (data.Code === 1000) {
              self.$messageTip.success(data.Msg);  
              self.loadBlacklist();
            } else {
              self.$messageTip.warning(data.Msg); 
            }
          });
        })
        .catch((ex) => {
          this.$messageTip.info("已取消加入黑名单！"); 
        });
    },
    //分页插件事件
    pageListInfo(par) {
      this.formSearch.page = par.currentPage;
      this.formSearch.limit = par.pageSize;
      this.loadInterfaceWarning();
    },
    //第二个分页插件事件
    pageListInfo1(par) {
      this.formSearch1.page = par.currentPage;
      this.formSearch1.limit = par.pageSize;
      this.loadBlacklist();
    },
    //搜索事件
    handleSearch() {
      this.formSearch.page = 1;
      this.formSearch.limit = 15;
      this.loadInterfaceWarning();
    },
    //第二个搜索事件
    handleSearch1() {
      this.formSearch1.page = 1;
      this.formSearch1.limit = 15;
      this.loadBlacklist();
    },

    //时间格式化
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property];
      if (daterc != null) {
        return daterc.slice(0, 10);
      }
    },
    getTime(time) {
      var date = new Date(time);
      var y = date.getFullYear();
      var m =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return y + "-" + m + "-" + d;
    }
  }
};
</script>
<style lang="scss" scoped>
.optbtns {
  font-size: 14px;
  font-family: " Microsoft YaHei";
  color: #4c4f53;
}
</style>
